//
//  XJEmojiPageCell.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/28.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

//列数
let XJEmojiKeyboardMaxCol = 7

//行数
let XJEmojiKeyboardMaxRow = 3

//每页显示的表情数
let XJEmojiKeyboardPageEmojiCount = XJEmojiKeyboardMaxCol * XJEmojiKeyboardMaxRow - 1

class XJEmojiPageCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 布局界面
    private func setupUI() {
        
        backgroundColor = UIColor.whiteColor()
        addChildBtn()
        
        contentView.addSubview(deleteBtn)
        contentView.addSubview(recentMsgLabel)
        
        recentMsgLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }
        
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        contentView.addGestureRecognizer(longPress)
    }
    
    
    
    //保存20个按钮的数组
    private lazy var enmotionBtnArr: [XJEmoticonBtn] = []
    
    /// 供外界设置cell数据
    var emotions: [XJEmojiModel]?{
        
        didSet{
            
            guard let emojis = emotions else{
                return
            }
            //先隐藏所有按钮
            for value in enmotionBtnArr {
                value.hidden = true
            }
            //先判断再遍历表情数组,设置表情数据
            for(index,value) in emojis.enumerate() {
                //取出按钮
                let btn = enmotionBtnArr[index]
                btn.hidden = false
                
                btn.emoticon = value

            }
        }
    }
    
    /// 供外界设置最近显示表情label显示或隐藏
    var indexPath: NSIndexPath?{
        didSet{
            recentMsgLabel.hidden = indexPath?.section != 0
        }
    }
    // MARK: - 添加20个表情
    
    /**
     添加20个表情按钮
     */
    private func addChildBtn(){
        
        let maxCount = XJEmojiKeyboardPageEmojiCount
        for _ in 0..<maxCount {
            
            let btn = XJEmoticonBtn()
            btn.addTarget(self, action: "didClickEmoticonBtn:", forControlEvents: .TouchUpInside)
            btn.titleLabel?.font = UIFont.systemFontOfSize(33)
            contentView.addSubview(btn)
            enmotionBtnArr.append(btn)
        }
    }
    
    // MARK: 表情按钮的点击事件
    
    /**
    长按显示popView
    */
    @objc private func longPress(ges: UILongPressGestureRecognizer){
        
        let location = ges.locationInView(ges.view)
        
        //找到位置对应的按钮
        func btnWithLocation(location: CGPoint) -> XJEmoticonBtn? {
            for value in enmotionBtnArr {
                
                if CGRectContainsPoint(value.frame, location){
                    
                    return value
                }
            }
            return nil
        }
        
        //通过点找到对应的表情按钮
        guard let btn = btnWithLocation(location) else{
            popView.removeFromSuperview()
            return
        }
        
        switch ges.state{
        
        case .Began,.Changed:
            let window = UIApplication.sharedApplication().windows.last!
            
            //坐标转换：将按钮在contentView里面的坐标值转换到window上面
            let rect = btn.superview!.convertRect(btn.frame, toView: window)
            
            //popview位置
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            
            //给popview上的按钮赋值
            print(popView.popViewBtn)
            popView.popViewBtn.emoticon = btn.emoticon
            
            window.addSubview(popView)
        default:
            popView.removeFromSuperview()
            
        }
        
    }
    /**
     点击表情
     */
    @objc private func didClickEmoticonBtn(btn: XJEmoticonBtn){
        
        //保存最近表情
        XJEmojiKeyboardViewModel.sharedEmojiViewModel.saveRecentEmoticon(btn.emoticon!)
        
        //表情按钮点击发送通知
        NSNotificationCenter.defaultCenter().postNotificationName("XJEmoticonBtnClickNotification", object: self, userInfo: ["emoticon": btn.emoticon!])
        
        let window = UIApplication.sharedApplication().windows.last!
        let popView = XJEmoticonPopView.popView()
        
        //坐标转换：将按钮在contentView里面的坐标值转换到window上面
        let rect = btn.superview!.convertRect(btn.frame, toView: window)
        
        //popview位置
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        
        //warning
        //给popview上的按钮赋值
        print(btn.emoticon)
        print(popView.popViewBtn)
         popView.popViewBtn.emoticon = btn.emoticon
        
        window.addSubview(popView)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
    }
    /**
     点击删除按钮
     */
    @objc private func didClickDeleteBtn(){
    
    NSNotificationCenter.defaultCenter().postNotificationName("XJEmoticonDeleteBtnClickNotificaton", object: nil, userInfo: nil)
    }
    
    
    /**
     设置按钮的frame
     */
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemW = self.frame.width / CGFloat(XJEmojiKeyboardMaxCol)
        let itemH = (self.frame.height  - 20 ) / CGFloat(XJEmojiKeyboardMaxRow)
        
        for(index,value) in enmotionBtnArr.enumerate() {
            
            let colIndex = index % XJEmojiKeyboardMaxCol
            let rowIndex = index / XJEmojiKeyboardMaxCol
            
            let itemX = CGFloat(colIndex) * itemW
            let itemY = CGFloat(rowIndex) * itemH
            
            value.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
        }
        
        let deleteBtnX = self.frame.width - itemW
        let deleteBtnY = self.frame.height - itemH - 20
        deleteBtn.frame = CGRect(x: deleteBtnX, y: deleteBtnY, width: itemW, height: itemH)
    }
    
    // MARK: - 懒加载控件
    
    private lazy var popView: XJEmoticonPopView = {
    
        let popView = XJEmoticonPopView.popView()
    
        return popView
    }()
    
    /// 懒加载删除按钮
    private lazy var deleteBtn: UIButton = {
    
        let deleteBtn = UIButton()
        deleteBtn.addTarget(self, action: "didClickDeleteBtn", forControlEvents: .TouchUpInside)
        
        deleteBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        deleteBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        
        return deleteBtn
    
    }()
    /// 懒加载最近表情显示的label
    private lazy var recentMsgLabel: UILabel = {
    
        let msgLabel = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 14)
        msgLabel.text = "最近使用的表情"
        return msgLabel
    
    }()
    
}